package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

//菜品管理
@RestController
@Slf4j
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private RedisTemplate redisTemplate;

//    新增菜品
    @PostMapping
    public R save(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());

        dishService.saveWithFlavor(dishDto);
//        清除每个分类下的菜品缓存数据
        String key="dish_"+dishDto.getCategoryId();
        redisTemplate.delete(key);
        return R.success("新增菜品成功");

    }

//    菜品分页查询
    @GetMapping("/page")
    public R page(int page,int pageSize,String name){
        Page<DishDto> dishDtoPage = dishService.pageByName(page, pageSize, name);
        return R.success(dishDtoPage);
    }
//根据id进行查询
    @GetMapping("{id}")
    public R getById(@PathVariable Long id){
        DishDto byIdWithFlavor = dishService.getByIdWithFlavor(id);
        return R.success(byIdWithFlavor);
    }
//    修改菜品
    @PutMapping
    public R update(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());
        dishService.updateWithFlavor(dishDto);
        //        清除每个分类下的菜品缓存数据
        String key="dish_"+dishDto.getCategoryId();
        redisTemplate.delete(key);
        return R.success("修改成功");
    }

//    根据条件查询对应的菜品数据
    @GetMapping("/list")
    public R list(Dish dish){
        List<DishDto> dishDtoList=null;
//        动态构造key
        String key="dish_"+dish.getCategoryId();
//        先从redis获取数据
        dishDtoList= (List<DishDto>) redisTemplate.opsForValue().get(key);
        if(dishDtoList!=null){
//            如果存在，直接返回，无需查询数据库
            return R.success(dishDtoList);
        }else {
            redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);
        }
        //构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        //添加条件，查询状态为1（起售状态）的菜品
        queryWrapper.eq(Dish::getStatus,1);
//        queryWrapper.like(StringUtils.isNotEmpty(dish.getName()),Dish::getName,dish::getName);

        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(queryWrapper);
        List<DishDto> resultList=list.stream().map((dishItem)->{
//            每循环一次构建一个dto
            DishDto dishDto = new DishDto();
//            将dish中的数据拷贝至dto
            BeanUtils.copyProperties(dishItem,dishDto);
//            查询这个菜品的口味信息
            LambdaQueryWrapper<DishFlavor> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(DishFlavor::getDishId,dishItem.getId());
            List<DishFlavor> dishFlavorList = dishFlavorService.list(queryWrapper1);

//            将口味信息设置到dto中
            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());
        return R.success(resultList);
    }


//    删除菜品
    @DeleteMapping
    public R delete(@RequestParam List<Long> ids){
        log.info("ids:{}",ids);
//        dishService.removeByIds(ids);
        dishService.removeWithFlavor(ids);
        return R.success("菜品数据删除成功");
    }

//    菜品的起售和停售
    @PostMapping("/status/{status}")
    public R updateStatus(@PathVariable Integer status,@RequestParam List<Long> ids){
        log.info("ids:{}",ids);
        dishService.updateStatus(status,ids);
        return R.success("菜品状态修改成功");
    }
}
